<template>
  <div id="wrap" class="wrap">
    <div id="box">
      <div id="marquee">{{text}}</div>
      <div id="copy"></div>
    </div>
    <div id="node">{{text}}</div>
  </div>
</template>

<script>
  export default {
    name: "ScrollText",
    props: {
      text: {
        type: String,
        required: true
      },
      waitMS: {
        type: Number,
        default() {
          //默认等待3秒后开始滚动
          return 3000;
        }
      }
    },
    data() {
      return {
      }
    },
    methods: {
      move () {
        // 获取文字text 的计算后宽度  （由于overflow的存在，直接获取不到，需要独立的node计算）
        let textWidth = document.getElementById('node').getBoundingClientRect().width;
        let marquee = document.getElementById('marquee');
        let boxWidth = document.getElementById('wrap').getBoundingClientRect().width;
        if (textWidth <= boxWidth) {
          return;
        }
        let copy = document.getElementById('copy');
        copy.innerText = this.text; // 文字副本填充
        let distance = 10; // 位移距离
        // 设置位移
        setInterval(function () {
          distance = distance - 1;
          // 如果位移超过文字宽度，则回到起点
          if (-distance >= textWidth) {
            distance = 16
          }
          marquee.style.transform = 'translateX(' + distance + 'px)';
          copy.style.transform = 'translateX(' + distance + 'px)';
        }, 40)
      }
    },
    // 把父组件传入的arr转化成字符串
    created: function () {
      setTimeout(this.move, this.waitMS);
    }
  }
</script>

<style scoped lang="less">
  .wrap {
    overflow: hidden;
    background: white;
  }
  #box {
    width: 500%;
  }
  #box div {
    float: left;
  }
  #marquee {
    margin: 0 16px 0 16px;
  }
  #node {
    position: absolute;
    z-index: -99;
    top: -99px;
    white-space: nowrap;
  }
</style>
